package com.hz.api.admin.web.config.thread;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步线程池
 * <p>线程使用指定bean-name</p>
 * @author xieqiyong
 */
@Configuration
@Slf4j
public class AsyncThreadConfig implements AsyncConfigurer {

  @Value("${async.pool.max.size:50}")
  private int corePoolMaxSize;
  @Value("${async.pool.core.size:8}")
  private int corePoolCoreSize;
  @Value("${async.pool.queue.size:1000}")
  private int queueCapacity;
  @Value("${async.pool.keep.alive:60}")
  private int keepAliveSeconds;

  /**
   * 处理平台异步消息
   * @return Executor
   */
  @Bean("taskExecutor")
  public Executor taskExecutor() {
    ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
    threadPoolTaskExecutor.setCorePoolSize(corePoolCoreSize);
    threadPoolTaskExecutor.setMaxPoolSize(corePoolMaxSize);
    threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
    threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
    threadPoolTaskExecutor.setThreadNamePrefix("taskExecutor-");
    threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    threadPoolTaskExecutor.initialize();
    return threadPoolTaskExecutor;
  }

  /**
   * 处理内部调用异步消息
   * @return Executor
   */
  @Bean("invokeMessageExecutor")
  public Executor invokeMessageExecutor(){
    ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
    threadPoolTaskExecutor.setCorePoolSize(corePoolCoreSize);
    threadPoolTaskExecutor.setMaxPoolSize(corePoolMaxSize);
    threadPoolTaskExecutor.setQueueCapacity(100);
    threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
    threadPoolTaskExecutor.setThreadNamePrefix("invokeMessageExecutor-");
    threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    threadPoolTaskExecutor.initialize();
    return threadPoolTaskExecutor;
  }

  @Override
  public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    return (Throwable ex, Method method, Object... params) -> {
      log.error("异步执行出现异常 {}，方法：{}, 参数为：{}",ex.getMessage(), method.getName(), Arrays.toString(params));
    };
  }
}
